package com.cube.share.jackson.util;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @author poker.li
 * @date 2021/10/26 16:35
 * <p>
 * 字符转义工具类
 */
public class EscapeUtil {

    /**
     * 将一字符串中的指定字符转义
     *
     * @param raw           原始字符传
     * @param needsToEscape 需要转义的字符数组
     * @return 结果
     */
    public static String escape(String raw, char[] needsToEscape) {
        if (StringUtils.isBlank(raw) || ArrayUtils.isEmpty(needsToEscape)) {
            return raw;
        }
        StringBuilder stringBuilder = new StringBuilder();
        char[] charArray = raw.toCharArray();
        for (char ch : charArray) {
            for (char escape : needsToEscape) {
                if (ch == escape) {
                    stringBuilder.append('\\');
                    break;
                }
            }
            stringBuilder.append(ch);
        }
        return stringBuilder.toString();
    }
}
